package com.sk.weichat.ui.contacts.label;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.R;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.Label;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.LabelDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @author lzs
 * @date 2019/9/16
 * Email:343067508@qq.com
 **/
public class LabelActivity2 extends BaseActivity {

    private static final int request_edit_label = 6723;
    private static final int request_create_label = 3452;
    private List<Label> labelList = new ArrayList<>();
    private BaseQuickAdapter<Label, BaseViewHolder> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_label2);
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText("标签");

        ImageView imgRight = (ImageView) findViewById(R.id.iv_title_right);
        imgRight.setImageResource(R.mipmap.icon_more_black);
        imgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (labelList.size() >= 20) {
                    //判断标签是否超过最大数
                    ToastUtil.showToast(mContext, getString(R.string.tips_max_label_size));
                } else {
                    CreateLabelActivity2.startCreateLabelActivity2ForResult(LabelActivity2.this, request_create_label, null, null);
                }

            }
        });
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        adapter = new BaseQuickAdapter<Label, BaseViewHolder>(R.layout.item_label_edit, labelList) {

            @Override
            protected void convert(BaseViewHolder holder, Label item) {
                holder.addOnClickListener(R.id.tv_delete, R.id.content);

                List<String> userIds = JSON.parseArray(item.getUserIdList(), String.class);
                if (userIds != null) {
                    String groupName = item.getGroupName();
                    if (groupName.length() > 12) {
                        //限制12位
                        groupName = groupName.substring(0, 12) + "...";
                    } else {

                    }
                    holder.setText(R.id.tv_label, groupName + "(" + userIds.size() + ")");
                    String userNames = "";
                    if (userIds != null && userIds.size() > 0) {
                        for (int i = 0; i < userIds.size(); i++) {
                            Friend friend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), userIds.get(i));
                            if (friend != null) {
                                if (i == userIds.size() - 1) {
                                    userNames += TextUtils.isEmpty(friend.getRemarkName()) ? friend.getNickName() : friend.getRemarkName();
                                } else {
                                    userNames += TextUtils.isEmpty(friend.getRemarkName()) ? friend.getNickName() + "，" : friend.getRemarkName() + "，";
                                }
                            }
                        }
                        holder.setText(R.id.tv_users, userNames);
                    } else {
                        holder.setText(R.id.tv_users, "");
                    }
                }

            }
        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_delete) {
                    //删除
                    deleteLabel(labelList.get(position));
                }
                if (view.getId() == R.id.content) {
                    //跳转编辑标签
                    Label label = labelList.get(position);
                    if (label != null) {
                        CreateLabelActivity2.startCreateLabelActivity2ForResult(LabelActivity2.this, request_edit_label, label, (ArrayList<Label>) labelList);
                    }
                }
            }
        });
        recyclerView.setAdapter(adapter);
        getLabels();
    }

    // 删除标签
    private void deleteLabel(final Label label) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("groupId", label.getGroupId());
        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_DELETE)
                .params(params)
                .build()
                .execute(new BaseCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ObjectResult<Label> result) {
                        if (result.getResultCode() == 1) {
                            //删除成功
                            int index = labelList.indexOf(label);
                            labelList.remove(label);
                            adapter.notifyItemRemoved(index);
                            //删除本地
                            LabelDao.getInstance().deleteLabel(coreManager.getSelf().getUserId(),label.getGroupId());
                            adjustEmpty(labelList.size() == 0);
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    private void getLabels() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().FRIENDGROUP_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<Label>(Label.class) {
                    @Override
                    public void onResponse(ArrayResult<Label> result) {
                        if (result.getResultCode() == 1) {
                            if (result.getData() == null || result.getData().size() == 0) {
                                adjustEmpty(true);
                            } else {
                                adjustEmpty(false);
                                labelList.clear();
                                labelList.addAll(result.getData());
                                adapter.notifyDataSetChanged();

                            }
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            getLabels();
        }
    }

    private void adjustEmpty(boolean isEmpty) {
        if (isEmpty) {
            findViewById(R.id.iv_empty).setVisibility(View.VISIBLE);
            findViewById(R.id.tv1).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_empty).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.iv_empty).setVisibility(View.GONE);
            findViewById(R.id.tv1).setVisibility(View.GONE);
            findViewById(R.id.tv_empty).setVisibility(View.GONE);
        }
    }

}
